package org.chickymate.scrumboard.client;

import org.chickymate.scrumboard.client.model.Board;
import org.chickymate.scrumboard.client.model.LoginInfo;
import org.chickymate.scrumboard.client.presenter.AppController;
import org.chickymate.scrumboard.client.service.BackLogItemService;
import org.chickymate.scrumboard.client.service.BackLogItemServiceAsync;
import org.chickymate.scrumboard.client.service.BoardService;
import org.chickymate.scrumboard.client.service.BoardServiceAsync;
import org.chickymate.scrumboard.client.service.LoginService;
import org.chickymate.scrumboard.client.service.LoginServiceAsync;
import org.chickymate.scrumboard.client.view.CreateBoardView;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class ScrumBoard implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final BackLogItemServiceAsync backLogItemService = GWT
			.create(BackLogItemService.class);
	
	private LoginInfo loginInfo;
	private VerticalPanel loginPanel = new VerticalPanel();
	private Label loginLabel = new Label("Please sign in to your Google Account to access the application.");
	private Anchor signInLink = new Anchor("Sign In");
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		
		LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
		
			@Override
			public void onFailure(Throwable caught) {
				loadLogin();				
			}

			@Override
			public void onSuccess(LoginInfo result) {
				loginInfo = result;
				if(loginInfo.isLoggedIn()){
					final HandlerManager eventBus = new HandlerManager(null);
					AppController appViewer = new AppController(eventBus,loginInfo);
					appViewer.go(RootPanel.get());
				}else{
					loadLogin();					
				}				
			}
			
		});		
	}
	
	private void loadLogin(){
		signInLink.setHref(loginInfo.getLoginUrl());
		loginPanel.add(loginLabel);
		loginPanel.add(signInLink);
		RootPanel.get("login").add(loginPanel);
	}
	
}
